package com.ycwl.aiLive_2d.aspectj;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * @date 2022年10月13日 13:55
 * 入参参数打印类
 */
@Aspect
@Component
public class RequestParameterAspectj {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestParameterAspectj.class);

    @Pointcut("execution(* com.ycwl.aiLive_2d.controller.*.*.*(..))")
    public void classPackage() {

    }

    @Around("classPackage()")
    public Object parameterPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            final HttpServletRequest request = requestAttributes.getRequest();
            String requestURI = request.getRequestURI();
            String method = request.getMethod();

            HashSet<String> parameterValueSet = new HashSet<>();
            Object[] requestParameterValue = joinPoint.getArgs();
            for (Object o : requestParameterValue) {
                if (!(o instanceof HttpServletRequest || o instanceof HttpServletResponse)) {
                    parameterValueSet.add(String.valueOf(o));
                }
            }

            Enumeration<String> parameterNames = request.getParameterNames();
            Map<String, String> parameterUrlMap = new HashMap<>();
            while (parameterNames.hasMoreElements()) {
                String parameterName = parameterNames.nextElement();
                String parameterValue = request.getParameter(parameterName);
                parameterUrlMap.put(parameterName, parameterValue);
            }

            if (parameterUrlMap.isEmpty()) {
                LOGGER.info("当前请求的路径为-> {} 请求方式为-> {} 参数为-> {}", requestURI, method, JSON.toJSONString(parameterValueSet));
            } else {
                LOGGER.info("当前请求的路径为-> {} 请求方式为-> {} 参数为-> {} 路径传参为-> {}", requestURI, method,
                        JSON.toJSONString(parameterValueSet), JSON.toJSONString(parameterUrlMap));
            }
        }
        return joinPoint.proceed();
    }
}
